<template>
  <div>
    <el-scrollbar height="850px">
      <div class="info_container">
        <el-card>
          <template #header>
            <div class="title_main">
              <span class="title"></span>
              <span class="note"> 设备基本信息</span>
            </div>
          </template>
          <div class="card_body">
            <div class="card_body1">
              <img
                src="@/assets/img/zaixian.png"
                style="width: 100px; height: 100px"
                v-if="BasicInfo.online"
              />
              <img
                src="@/assets/img/lixian.png"
                style="width: 100px; height: 100px"
                v-else
              />

              <span
                style="
                  font-weight: 400;
                  color: #00daa6;
                  font-size: 18px;
                  margin-left: 15px;
                "
                v-if="BasicInfo.online"
                >在线状态</span
              >
              <span
                style="
                  font-weight: 400;
                  color: #ed5f5c;
                  font-size: 18px;
                  margin-left: 15px;
                "
                v-else
                >离线状态</span
              >
            </div>
            <div class="card_body2">
              <el-row style="font-size: 18px; color: #606266; font-weight: 400">
                <el-col :span="8">
                  <div>
                    <span>设备序列号：</span><span>{{ BasicInfo.imei }}</span>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div>
                    <span>设备型号：</span
                    ><span>{{ BasicInfo.deviceModel }}</span>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div>
                    <span>设备类型：</span><span>{{ BasicInfo.typeName }}</span>
                  </div>
                </el-col>
                <el-col
                  :span="8"
                  style="
                    margin-top: 30px;
                    display: flex;
                    align-items: center;
                    height: 44px;
                  "
                >
                  <div style="display: flex; align-items: center">
                    <span>设备电量：</span
                    ><span style="display: inline-block">
                      <BatteryDisplay
                        :quantity="BasicInfo.remainingPower"
                        :width="100"
                        :height="35"
                        v-if="BasicInfo.remainingPower >= 0"
                      ></BatteryDisplay>
                      <span style="color: red" v-else>未知</span>
                    </span>
                  </div>
                </el-col>
                <el-col
                  :span="8"
                  style="margin-top: 30px; display: flex; align-items: center"
                >
                  <div
                    style="display: flex; display: flex; align-items: center"
                  >
                    <span>监测数据：</span>

                    <span
                      v-for="item in BasicInfo.deviceGatherDataList"
                      :key="item.id"
                    >
                      {{ item.gatherDatald }}
                      <img
                        src="@/assets/img/gaojing.png"
                        style="width: 44px; margin-left: 10px"
                        v-if="item.gatherDataId == '0'"
                      />
                      <img
                        src="@/assets/img/jiankang.png"
                        style="width: 44px; margin-left: 10px"
                        v-if="item.gatherDataId == '1'"
                      />
                      <img
                        src="@/assets/img/jiankong.png"
                        style="width: 44px; margin-left: 10px"
                        v-if="item.gatherDataId == '3'"
                      />
                      <img
                        src="@/assets/img/shuimian.png"
                        style="width: 44px; margin-left: 10px"
                        v-if="item.gatherDataId == '2'"
                      />
                    </span>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-card>
        <div v-for="item in BasicInfo.deviceGatherDataList" :key="item.id">
          <el-card style="margin-top: 15px" v-if="item.gatherDataId == '0'">
            <template #header>
              <div class="title_main">
                <span class="title"></span>
                <span class="note"> 即时报警</span>
              </div>
            </template>
            <div style="display: flex; justify-content: start; flex-wrap: wrap">
              <div
                class="item"
                style="cursor: pointer"
                v-for="(item, index) in warningData"
                :key="index"
                :class="item.deviceStatus !== '-1' ? 'dangers' : ''"
                @click="openDialogAlert(item)"
              >
                <div>
                  <img :src="item.iconUrl" style="width: 45px; height: 45px" />
                </div>
                <div style="margin-left: 8px">
                  <span style="font-size: 18px"
                    ><span>
                      {{
                        device_name.find((i) => i.value == item.deviceType)
                          ? device_name.find((i) => i.value == item.deviceType)
                              .label
                          : ""
                      }}：</span
                    ><span>{{
                      alarm_type.find((i) => i.value == item.deviceStatus)
                        ? alarm_type.find((i) => i.value == item.deviceStatus)
                            .label
                        : ""
                    }}</span></span
                  >
                  <span
                    style="
                      display: block;
                      font-size: 14px;
                      color: #888888;
                      margin-top: 6px;
                    "
                    >{{ item.lastUpdatedTime }}</span
                  >
                </div>
                <div
                  style="position: absolute; right: 10px; top: 5px"
                  v-if="item.deviceStatus !== '-1'"
                >
                  <img
                    src="@/assets/img/liangdeng.png"
                    style="width: 23px; height: 23px"
                  />
                </div>
              </div>
            </div>
          </el-card>
          <el-card style="margin-top: 15px" v-if="item.gatherDataId == '1'">
            <template #header>
              <div class="title_main">
                <span class="title"></span>
                <span class="note">健康指标</span>
              </div>
            </template>
            <div style="display: flex; justify-content: start; flex-wrap: wrap">
              <div
                class="item"
                style="cursor: pointer"
                v-for="(item, index) in healthData"
                :key="index"
                :class="item.state == false ? 'dangers' : ''"
                @click="openDialogHealthIndex(item)"
              >
                <div>
                  <img :src="item.iconUrl" style="width: 45px; height: 45px" />
                </div>
                <div style="margin-left: 10px">
                  <span style="font-size: 18px"
                    ><span>{{ item.indexName }}：</span
                    ><span>{{ item.indexValue }}{{ item.unit }}</span></span
                  >
                  <span
                    style="
                      display: block;
                      font-size: 14px;
                      color: #888888;
                      margin-top: 6px;
                    "
                    >{{ item.timeBegin }}
                  </span>
                </div>
                <div
                  style="position: absolute; right: 10px; top: 5px"
                  v-if="item.state == false"
                >
                  <img
                    src="@/assets/img/liangdeng.png"
                    style="width: 23px; height: 23px"
                  />
                </div>
              </div>
            </div>
          </el-card>
          <el-card style="margin-top: 15px" v-if="item.gatherDataId == '2'">
            <template #header>
              <div class="title_main">
                <span class="title"></span>
                <span class="note">睡眠信息</span>
                <span style="margin-left: 15px">
                  <el-date-picker
                    style="width: 120px"
                    @change="changeDate"
                    v-model="value1"
                    type="date"
                    placeholder="选择日期"
                    size="small"
                    value-format="YYYY-MM-DD"
                  />
                </span>
              </div>
            </template>
            <div>
              <el-row>
                <el-col :span="6">
                  <div style="display: flex; padding: 10px 15px">
                    <div>
                      <span>用户实时状态：</span>
                      <span>
                        <el-tag
                          class="ml-2"
                          type="success"
                          style="margin-left: 5px"
                          v-if="bedStatus == '1'"
                          >在床</el-tag
                        >
                        <el-tag
                          class="ml-2"
                          type="warning"
                          style="margin-left: 5px"
                          v-else
                          >离床</el-tag
                        >
                      </span>
                    </div>
                  </div>
                  <div>
                    <echarts_status :perData="perData"></echarts_status>
                  </div>
                </el-col>
                <el-col :span="18">
                  <div>
                    <echarts_par :imei="routeValue"></echarts_par>
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-card>
          <el-card style="margin-top: 15px" v-if="item.gatherDataId == '3'">
            <template #header>
              <div class="title_main">
                <span class="title"></span>
                <span class="note">实时视频</span>
              </div>
            </template>
            <div>
              <el-row :gutter="30">
                <el-col :span="24">
                  <video1></video1>
                </el-col>
              </el-row>
            </div>
          </el-card>
        </div>
        <el-card
          class="box-card"
          shadow="always"
          style="background: #fafafa; margin-top: 15px"
        >
          <div style="text-align: right">
            <el-button @click="goCancel">返 回</el-button>
          </div>
        </el-card>
      </div>
    </el-scrollbar>

    <el-dialog
      :before-close="handleCloseAlarm"
      v-model="open"
      title="即时报警"
      append-to-body
      width="1000px"
      v-if="open"
      :close-on-click-modal="false"
    >
      <el-form :model="form">
        <el-form-item label="设备类型" prop="categoryId">
          <el-select
            v-model="form.deviceType"
            placeholder="请选择设备类型"
            style="width: 150px"
            @change="selectChange"
          >
            <el-option
              v-for="dict in deviceTypeSelect"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div>
        <el-table v-loading="loading" :data="postList" stripe border>
          <el-table-column
            prop="alertTime"
            label="告警时间"
            align="center"
            width="200"
          />
          <el-table-column
            label="告警信息"
            align="center"
            width="150"
            prop="alertInfo"
          ></el-table-column>
          <el-table-column
            label="告警终端"
            align="center"
            width="200"
            prop="alertTerminal"
          ></el-table-column>
          <el-table-column
            label="告警地址"
            align="center"
            prop="alertAddress"
          ></el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="form.page"
          v-model:limit="form.limit"
          @pagination="getTableList"
        />
      </div>
    </el-dialog>

    <el-dialog
      :before-close="handleCloseHealth"
      v-model="open1"
      title="健康指标"
      append-to-body
      width="1200px"
      v-if="open1"
      :close-on-click-modal="false"
    >
      <el-form :model="form1">
        <el-form-item label="指标名称" prop="categoryId">
          <el-select
            v-model="form1.indexId"
            placeholder="请选择指标名称"
            style="width: 150px"
            @change="healthIndexSelectChange"
          >
            <el-option
              v-for="dict in healthIndexNameArr"
              :key="dict.indexId"
              :label="dict.indexName"
              :value="dict.indexId"
            ></el-option>
          </el-select>
          <el-radio-group
            v-model="tabData"
            size="small"
            style="margin-left: 20px"
          >
            <el-radio-button label="trend">查看趋势</el-radio-button>
            <el-radio-button label="data">数据详情</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div v-if="tabData == 'trend'">
        <echarts_line
          :basicInfo="BasicInfo.imei"
          :rawData="healthData"
          :healthSelectData="form1.indexId"
          :dictData="index_name"
        ></echarts_line>
      </div>
      <div v-if="tabData == 'data'">
        <el-table
          :data="indexDataArr"
          stripe
          border
          :cell-style="handleChangeCellStyle"
        >
          <el-table-column
            prop="timeBegin"
            label="监测时间"
            align="center"
            width="250"
          />
          <el-table-column
            prop="indexValue"
            label="测量值"
            align="center"
            width="150"
          />
          <el-table-column label="测量结果" align="center" width="200">
            <template v-slot:default="scope">
              <span>{{ measurement(scope.row) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="测量地址" align="center">
            <template v-slot:default="scope">
              <span>{{ BasicInfo.address }}</span>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="healthTotal > 0"
          :total="healthTotal"
          v-model:page="form1.page"
          v-model:limit="form1.limit"
          @pagination="getIndexTableList"
        />
      </div>
    </el-dialog>
  </div>
</template>
<script setup name="info">
import axios from "axios";
import BatteryDisplay from "@/views/equipmentManagement/deviceRegistration/BatteryDisplay.vue";
import echarts_status from "@/views/equipmentManagement/info/echarts_status.vue";
import echarts_par from "@/views/equipmentManagement/info/echarts_par.vue";
import echarts_line from "@/views/equipmentManagement/info/line.vue";
import video1 from "@/views/equipmentManagement/info/video.vue";
import { AppKey, Secret } from "@/utils/auth";
import moment from "moment";
import {
  getDeviceBasicInfo,
  getgetBedBeltStatusInfo,
  getSleepReportPie,
  getTerminalAlertInfo,
  getHealthIndex,
  getDeviceTypeAlertData,
  getIndexTableData,
} from "@/api/equipment/index";
// import { ref, watch ,onMounted,useRoute} from 'vue';
const value1 = ref(moment().subtract(1, "days").format("YYYY-MM-DD"));
const { proxy } = getCurrentInstance();
const { device_name, alarm_type, index_name } = proxy.useDict(
  "device_name",
  "alarm_type",
  "index_name"
);
const route = useRoute();
const router = useRouter();
const open = ref(false);
const open1 = ref(false);
const warnType = ref([]);
const postList = ref([]);
const loading = ref(false);
const total = ref(0);
const healthTotal = ref(0);
const indexTotal = ref(0);
const tabData = ref("data");
const routeValue = ref("");
const BasicInfo = ref({});
const bedStatus = ref(null);
const perData = ref(null);
const warningData = ref([]);
const healthData = ref([]);
// 即时警报的设备类型下拉数组
const deviceTypeSelect = ref([]);
// 健康指标的指标名称的下拉数组
const healthIndexNameArr = ref([]);
// 健康指标的数组
const indexDataArr = ref([]);
const routedeviceModel = ref("");

const data = reactive({
  form: {
    limit: 10,
    page: 1,
  },
  form1: {
    limit: 10,
    page: 1,
  },
});

const { form, form1 } = toRefs(data);

// 关闭弹框-警告
const handleCloseAlarm = () => {
  (form.value.limit = 10), (form.value.page = 1), (open.value = false);
};

// 关闭弹框-健康
const handleCloseHealth = () => {
  (form1.value.limit = 10),
    (form1.value.page = 1),
    (open1.value = false),
    (tabData.value = "data");
};

// 健康指标的下拉列表选中时触发
const healthIndexSelectChange = (value) => {
  (form1.value.page = 1),
    // 重新发请求
    getIndexTableList();
};

// 给单元格设置颜色的函数
const handleChangeCellStyle = ({ row, column, rowIndex, columnIndex }) => {
  const lastMatch = test(row);
  // 进行比较
  if (lastMatch.upperLimit == null) {
    if (row.indexValue < lastMatch.lowerLimit) {
      return { color: "red" };
    } else {
      return { color: "black" };
    }
  } else if (lastMatch.lowerLimit == null) {
    if (row.indexValue > lastMatch.upperLimit) {
      return { color: "red" };
    } else {
      return { color: "black" };
    }
  } else {
    if (Number(row.indexValue) > Number(lastMatch.upperLimit)) {
      return { color: "red" };
    }

    if (Number(row.indexValue) < Number(lastMatch.lowerLimit)) {
      return { color: "red" };
    }

    return { color: "black" };
  }
};

// 写一个方法,封装匹配的代码，方便在其他地方用
const test = (data) => {
  // 在字典里拿到中文
  const match = index_name.value.find((item) => {
    return item.value == form1.value.indexId;
  });

  //在健康指标数据里根据中文进行匹配找到匹配的元素
  const lastMatch = healthData.value.find((item) => {
    return item.indexName == match.label;
  });

  return lastMatch;
};

// 写一个方法，测量结果比较，最终的结果显示在表格中
const measurement = (data) => {
  // console.log(data, "<<<=== data 测量结果函数 传进来当前行");
  const lastMatch = test(data);
  // 进行比较
  if (lastMatch.upperLimit == null) {
    if (data.indexValue < lastMatch.lowerLimit) {
      return "低于正常值";
    } else {
      return "正常";
    }
  } else if (lastMatch.lowerLimit == null) {
    if (data.indexValue > lastMatch.upperLimit) {
      return "高于正常值";
    } else {
      return "正常";
    }
  } else {
    if (Number(data.indexValue) > Number(lastMatch.upperLimit)) {
      return "高于正常值";
    }

    if (Number(data.indexValue) < Number(lastMatch.lowerLimit)) {
      return "低于正常值";
    }

    return "正常";
  }
};
// 写一个方法，专门用来请求健康指标-分页要用
const getIndexTableList = () => {
  // 组装参数
  const params = {
    limit: form1.value.limit,
    page: form1.value.page,
    imei: BasicInfo.value.imei,
    indexType: form1.value.indexId,
  };

  getIndexTableData(params)
    .then((res) => {
      indexDataArr.value = res.page.list;
      // 分页
      healthTotal.value = res.page.totalCount;
      form1.value.limit = res.page.pageSize;
      form1.value.page = res.page.currPage;
    })
    .catch((error) => {});
};

// 点击健康指标的元素
const openDialogHealthIndex = (data) => {
  // 打开弹框
  open1.value = true;
  // 第1次
  form1.value.indexId = data.indexId;
  // 拿表格数据
  getIndexTableList();
};

// 写一个方法，改造健康指标的数据
const healthIndexNameDataChange = (data) => {
  healthIndexNameArr.value = data.map((item) => {
    const obj = {
      indexId: item.indexId,
      indexName: item.indexName,
    };
    return obj;
  });
};

// 监听即时报警-下拉列表选中时
const selectChange = (value) => {
  form.value.page = 1;
  getTableList();
};
// 写一个方法，根据分页拿到表格数据
const getTableList = () => {
  // 组装参数
  const params = {
    limit: form.value.limit,
    page: form.value.page,
    imei: BasicInfo.value.imei,
    deviceType: form.value.deviceType,
    deviceModel: routedeviceModel.value,
  };

  getDeviceTypeAlertData(params)
    .then((res) => {
      console.log(res, "<<<=== res 表格数据");
      postList.value = res.page.list;
      total.value = res.page.totalCount;
    })
    .catch((error) => {
      console.log(error, "error");
    });
};

const openDialogAlert = (data) => {
  open.value = true;
  form.value.deviceType = data.deviceType;
  //打开弹框的时候就要发请求拿到表格数据
  getTableList();
};
// 写一个方法用来设备类型数据改造-注意字典后面要加value
const deviceTypeSelectChange = (data) => {
  const arr = data.map((item) => {
    return item.deviceType;
  });

  const some = [];
  arr.forEach((item) => {
    const res = device_name.value.find((data) => {
      return item == data.value;
    });
    some.push(res);
  });

  deviceTypeSelect.value = some;
};
function getScreen() {
  console.log("22222222222222", AppKey, Secret);
  let obj = {
    appKey: AppKey,
    appSecret: Secret,
  };
  // const formData = new URLSearchParams();
  // formData.append("appKey", "9mqitppidgce4y8n54ranvyqc9fjtsrl");
  // formData.append("appSecret", "096e76501644989b63ba0016ec5776");
  axios.post("https://open.ys7.com/api/lapp/token/get", obj).then((res) => {
    console.log("22222222222222222222222222", res);
  });
}
//睡眠
function changeDate(val) {
  getSleepReportPieData(routeValue.value, val);
}
//告警
function getTerminalAlertInfoData(deviceModel, id) {
  getTerminalAlertInfo(deviceModel, id).then((res) => {
    warningData.value = res.terminalAlertInfo;
    // 将数据进行改造
    deviceTypeSelectChange(res.terminalAlertInfo);
  });
}

function getHealthIndexData(id) {
  getHealthIndex(id).then((res) => {
    healthData.value = res.healthIndex.map((item) => ({
      ...item,
      state: calculateState(item),
    }));
    // 改造数据
    healthIndexNameDataChange(healthData.value);
  });
}
//睡眠
function getSleepReportPieData(id) {
  getSleepReportPie(id, value1.value).then((res) => {
    perData.value = res.sleepReportPie;
  });
}
function goCancel() {
  router.go(-1);
}
const calculateState = (item) => {
  const numericValue = parseFloat(item.indexValue);
  if (item.upperLimit && !item.lowerLimit) {
    // upperLimit 有值，lowerLimit 无值，判断 indexValue < upperLimit
    return !isNaN(numericValue) && numericValue < item.upperLimit;
  } else if (!item.upperLimit && item.lowerLimit) {
    // upperLimit 无值，lowerLimit 有值，判断 indexValue > lowerLimit
    return !isNaN(numericValue) && numericValue > item.lowerLimit;
  } else if (item.upperLimit && item.lowerLimit) {
    // upperLimit 和 lowerLimit 都有值，判断 (indexValue < upperLimit && indexValue > lowerLimit)
    return (
      !isNaN(numericValue) &&
      numericValue < item.upperLimit &&
      numericValue > item.lowerLimit
    );
  } else {
    // 其他情况，例如都没有值
    return false;
  }
};
//ji
function getBaseInfo(deviceModel, id) {
  getDeviceBasicInfo(deviceModel, id).then((res) => {
    BasicInfo.value = res.deviceBasicInfo;
    for (let i in BasicInfo.value.deviceGatherDataList) {
      if (BasicInfo.value.deviceGatherDataList[i].gatherDataId == "0") {
        getTerminalAlertInfoData(
          BasicInfo.value.deviceModel,
          BasicInfo.value.imei
        );
      }
      if (BasicInfo.value.deviceGatherDataList[i].gatherDataId == "1") {
        getHealthIndexData(BasicInfo.value.imei);
      }
      if (BasicInfo.value.deviceGatherDataList[i].gatherDataId == "2") {
        getBed(BasicInfo.value.imei);
        getSleepReportPieData(BasicInfo.value.imei);
      }
      if (BasicInfo.value.deviceGatherDataList[i].gatherDataId == "3") {
      }
    }
    // getBed(BasicInfo.value.imei);
    // getSleepReportPieData(BasicInfo.value.imei);
    // getTerminalAlertInfoData(BasicInfo.value.deviceModel, BasicInfo.value.imei);
    // getHealthIndexData(BasicInfo.value.imei);
  });
}
function getBed(id) {
  getgetBedBeltStatusInfo(id).then((res) => {
    bedStatus.value = res.bedBeltStatusInfo?.bed_status;
  });
}

const stopWatch = watch(
  () => route,
  (newVal, oldVal) => {
    routeValue.value = newVal.params.id;
    routedeviceModel.value = newVal.params.deviceModel;
    getBaseInfo(newVal.params.deviceModel, newVal.params.id);
    getScreen();
    // getBed(newVal.params.id);
    // getSleepReportPieData(newVal.params.id);
    // getTerminalAlertInfoData(newVal.params.deviceModel, newVal.params.id);
    // getHealthIndexData(newVal.params.id);
  },
  { immediate: true }
);

onBeforeUnmount(() => {
  stopWatch();
});
</script>
<style scoped lang="scss">
.scroll-container {
  max-height: 2000px; /* Set the maximum height for the scroll container */
}

.scroll-wrapper {
  height: 100%; /* Set the height of the scroll wrapper */
}
.info_container {
  padding: 20px;

  .title_main {
    display: flex;
    align-items: center;
    .title {
      width: 7px;
      height: 18px;
      line-height: 18px;
      background: #409eff;
      border-radius: 4px;
      display: inline-block;
    }
    .note {
      margin-left: 8px;
    }
  }
  .card_body {
    display: flex;
    .card_body1 {
      width: 15%;
      display: flex;
      align-items: center;
    }
    .card_body2 {
      width: 85%;
    }
  }
  .item {
    height: 50px;
    border-radius: 4px;
    width: 280px;
    height: 90px;
    margin-top: 10px;
    margin-right: 30px;
    display: flex;
    align-items: center;
    padding-left: 10px;
    position: relative;
  }
  .dangers {
    border: 2px solid #ed5f5c;
    box-shadow: -2px 2px 10px 5px #ed5f5c;
  }

  //:deep(.tab) .el-radio-group{
  //  //.el-radio-button{
  //  //  border: 1px solid #1CDBFE;
  //  //
  //  //}
  //  margin-bottom: 0!important;
  //  .el-radio-button__inner{
  //    background:#FFFFFF;
  //    color: #409EFF;
  //    border: 1px solid #409EFF;
  //  }
  //  .is-active .el-radio-button__inner{
  //    background: #409EFF;
  //    color: #FFFFFF;
  //  }
  //}
}
</style>
